package com.eastedu.superise.handler.basic;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.eastedu.client.file.model.FileInfoResponse;
import com.eastedu.converter.BasicResourceFileConverter;
import com.eastedu.manager.BasicResourceManager;
import com.eastedu.manager.FileManager;
import com.eastedu.repository.basic.mapper.BasicResourceFileMapper;
import com.eastedu.repository.basic.po.BasicResourceFilePO;
import com.eastedu.repository.basic.po.BasicResourcePO;
import com.eastedu.superise.handler.AbstractHistoricalDataHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.List;
import java.util.Objects;

/**
 * 处理zip格式微课
 * @author zhangzhishuai
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class FileInfoHistoricalDataHandler extends AbstractHistoricalDataHandler<BasicResourcePO> {

    private final FileManager fileManager;
    private final BasicResourceFileMapper basicResourceFileMapper;
    private final BasicResourceFileConverter basicResourceFileConverter;
    private final BasicResourceManager basicResourceManager;


    @Override
    protected String getSql() {
        return "SELECT * FROM t_basic_resource WHERE id IN (\n" +
                "'969657993862299648',\n" +
                "'969657992717254656',\n" +
                "'969650975004934144',\n" +
                "'969650491053555712',\n" +
                "'969650490080477184'\n" +
                ")";
    }

    @Override
    public void callback(BasicResourcePO po) throws SQLException {
        List<BasicResourceFilePO> basicResourceFilePoList = this.basicResourceFileMapper
                .selectList(Wrappers.lambdaQuery(BasicResourceFilePO.class)
                        .eq(BasicResourceFilePO::getBasicResourceId, po.getId()));
        basicResourceFilePoList.forEach(this::update);
        basicResourceManager.updateFileJsonByResourceId(String.valueOf(po.getId()), basicResourceFilePoList);

    }

    private void update(BasicResourceFilePO po) {
        FileInfoResponse fileInfoResponse = fileManager.getFileInfo(Long.valueOf(po.getFileId()));
        if (Objects.isNull(fileInfoResponse)) {
            log.warn("文件信息错误，跳过，ID：{}", po.getId());
            return;
        }
        this.basicResourceFileConverter.update(fileInfoResponse, po);
        this.basicResourceFileMapper.updateById(po);
        log.info("更新成功");
    }

}
